using Digitalmes.Application.Scada.Commands;
using Digitalmes.Domain;
using Digitalmes.Infrastructure.Scada.Extensions;
using ThingsEdge.Exchange.Contracts;

namespace Digitalmes.Infrastructure.Scada.Handlers;

/// <summary>
/// 扫批次料处理。
/// </summary>
internal sealed class ScanBatchHandler(ISender sender, ILogger<ScanBatchHandler> logger) : IScadaAskHandler
{
    public async Task<ScadaResult> HandleAsync(RequestMessage message, CancellationToken cancellationToken = default)
    {
        var barcode = message.GetString(TagDefinition.PLC_ScanBatch_Barcode);

        // 请求日志
        logger.LogInformation("[批次料扫码请求] {Barcode}, 产线：{LineName}，工位：{WsCode}，数据：{Message}",
            barcode ?? "",
            message.Schema.ChannelName,
            message.Schema.TagGroupName,
            message.Values.Select(s => new { s.TagName, s.Address, s.Value }).ToJson());

        if (string.IsNullOrWhiteSpace(barcode))
        {
            return LoggerHelper.LogAndReturn(logger, "批次料扫码响应", message.Schema.ChannelName, message.Schema.TagGroupName!, ErrorCode.E1501);
        }

        int qty = message.AsInt32(TagDefinition.PLC_ScanBatch_Qty) ?? 0; // 上料数量，未设置默认为 0。

        ScanBatchCommand command = new()
        {
            LineCode = message.Schema.ChannelName,
            WsCode = message.Schema.TagGroupName,
            Barcode = barcode,
            Qty = qty,
        };

        try
        {
            var result = await sender.Send(command, cancellationToken).ConfigureAwait(false);

            // 响应日志
            logger.LogInformation("[批次料扫码响应] {Barcode}, 产线：{LineName}，工位：{WsCode}，状态: {State}, 消息: [{InnerErrorCode}] {ErrMessage}, 回调值: {CallbackItems}",
               barcode,
               message.Schema.ChannelName,
               message.Schema.TagGroupName,
               result.State.ToString(),
               result.InnerErrorCode.ToString(),
               result.GetErrorMessage(),
               result.CallbackItems.ToJson() ?? "[]");

            return result;
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "[批次料扫码服务处理异常] {Barcode}, 产线：{LineName}，工位：{WsCode}",
                barcode,
                message.Schema.ChannelName,
                message.Schema.TagGroupName);
            return ScadaResult.Error();
        }
    }
}
